import { ModalForm } from '@ant-design/pro-components';
import { message } from 'antd';
import { bindWx } from '../service';
import { useModel } from 'umi';

const WxBindModal = (props: { visible: boolean; close: () => void }) => {
  const { wxAppId, wxLoginSwitch, wxRedirectUri } = useModel('wxconfig');
  const { visible, close } = props;
  const randomCode = String((Math.random() * 1000000) << 2);
  const hashChangeEv = (ev: HashChangeEvent) => {
    if (!wxLoginSwitch) return;
    console.log('WxBingModal hashChangeEv');
    const args = ev.newURL.split('?');
    if (args.length < 2) {
      message.error({
        content: '微信登录失败',
        key: 'bind_wx',
      });
      window.removeEventListener('hashchange', hashChangeEv);
      close();
      return;
    }
    const search = new URLSearchParams(args[1]);
    // 当前umi/history定义中无query属性，所以这里使用search
    // const search = new URLSearchParams(location.search);
    const code = search.get('code') || '';
    const state = search.get('state') || '';
    if (!code) {
      // 无法获取code属性，说明是微信登录失败
      message.error({
        content: '微信登录失败',
        key: 'bind_wx',
      });
      window.removeEventListener('hashchange', hashChangeEv);
      close();
      return;
    }
    if (state !== randomCode) {
      // 防止伪造state
      message.error({
        content: '微信登录失败',
        key: 'bind_wx',
      });
      window.removeEventListener('hashchange', hashChangeEv);
      close();
      return;
    }
    bindWx(code).then((res) => {
      if (res?.success) {
        message.success({
          content: '微信绑定成功',
          key: 'bind_wx',
        });
      } else {
        message.error({
          content: res?.message || '微信绑定失败',
          key: 'bind_wx',
        });
      }
      window.removeEventListener('hashchange', hashChangeEv);
      close();
    });
    return;
  };
  return (
    <ModalForm
      title="绑定微信"
      // trigger={
      //   <Button type="primary" size="small">
      //     绑定微信
      //   </Button>
      // }
      visible={visible}
      width={400}
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
        onCancel: () => {
          window.removeEventListener('hashchange', hashChangeEv);
          close();
        },
      }}
      onVisibleChange={(open) => {
        if (!wxLoginSwitch) return;
        if (!open) {
          window.removeEventListener('hashchange', hashChangeEv);
          return;
        }
        //@ts-ignore
        let WxLogin: WxLogin = window.WxLogin;
        if (!WxLogin) {
          const wxScript = document.createElement('script');
          wxScript.type = 'text/javascript';
          wxScript.src = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js';
          document.getElementById('root')?.appendChild(wxScript);
          wxScript.onload = () => {
            //@ts-ignore
            WxLogin = window.WxLogin;
            WxLogin({
              id: 'wx_login_container2',
              appid: wxAppId,
              scope: 'snsapi_login,snsapi_userinfo',
              redirect_uri: encodeURIComponent(`${wxRedirectUri}/#/account`),
              state: randomCode,
            });
            window.addEventListener('hashchange', hashChangeEv);
          };
        } else {
          WxLogin({
            id: 'wx_login_container2',
            appid: wxAppId,
            scope: 'snsapi_login,snsapi_userinfo',
            redirect_uri: encodeURIComponent(`${wxRedirectUri}/#/account`),
            state: randomCode,
          });
          window.addEventListener('hashchange', hashChangeEv);
        }
      }}
    >
      <div id="wx_login_container2"></div>
    </ModalForm>
  );
};

export default WxBindModal;
